package com.example.springbootchapter09.service;


import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${spring.mail.username}")
    private  String from;
    public void sendPlainTextEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
       try {
           mailSender.send(message);
           System.out.println("纯文本邮件发送成功");
       }catch  (MailException e) {
           System.out.println("纯文本邮件发送失败 " + e.getMessage());
           e.printStackTrace();
       }
    }
    public void sendAttachmentAndImageEmail(String to, String subject, String text, String attachmentPath, String imagePath) throws MessagingException, MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text, true);
        // 添加附件
        FileSystemResource attachment = new FileSystemResource(new File(attachmentPath));
        helper.addAttachment("附件文件名.pdf", attachment);
        // 添加图片
        FileSystemResource image = new FileSystemResource(new File(imagePath));
        helper.addInline("imageId", image);
        mailSender.send(message);
    }

    public void sendTemplateEmail(String to, String subject) throws MessagingException, IOException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        // 配置模板参数
        Context context = new Context();
        Map<String, Object> model = new HashMap<>();
        model.put("username", "John Doe");
        context.setVariables(model);
        // 渲染模板
        String htmlContent = templateEngine.process("emailTemplate", context);
        helper.setText(htmlContent, true);
        mailSender.send(message);
    }
}